package com.kaoshi.controller;

import com.kaoshi.dao.*;
import com.kaoshi.module.*;
import com.kaoshi.util.DataEntity;
import com.kaoshi.util.MathUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RequestMapping("/admin/home")
@Controller
public class HomeController {

    @Autowired
    private KaoshiDao kaoshidao;
    @Autowired
    private TestDao testdao;
    @Autowired
    private Test2Dao test2dao;
    @Autowired
    private Test3Dao test3dao;
    @Autowired
    private Test4Dao test4dao;
    @Autowired
    private BanjiDao banjidao;
    @Autowired
    private ExamDao examdao;
    @Autowired
    private ExamtimeDao examtimedao;

    /**
     * 加载首页
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request) {
        return "home/index";
    }

    /**
     * 获取用户考试列表
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/exam", method = RequestMethod.GET)
    public String exam(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        User user = (User) request.getSession().getAttribute("admin");
        if (user == null) {
            return "../../login";
        }
        Example example = new Example(Kaoshi.class);
        example.orderBy("state").asc();
        Criteria criteria = example.createCriteria();
        criteria.andEqualTo("bid", user.getBid());
        criteria.andEqualTo("nid", user.getNid());
        List<Kaoshi> kaoshis = kaoshidao.selectByExample(example);
        request.setAttribute("kaoshilist", kaoshis);
        return "home/exam";
    }

    /**
     * 获取试卷信息
     *
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/timu", method = RequestMethod.GET)
    public String timu(Integer id, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        User user = (User) request.getSession().getAttribute("admin");
        if (user == null) {
            return "../../login";
        }
        Kaoshi kaoshi = kaoshidao.selectByPrimaryKey(id);
        request.setAttribute("kaoshi", kaoshi);
        request.setAttribute("id", id);
        return "home/timu";
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        User user = (User) request.getSession().getAttribute("admin");
        if (user == null) {
            return "../../login";
        }
        Example example = new Example(Exam.class);
        example.createCriteria().andEqualTo("uid", user.getId()).andEqualTo("state", 1);
        List<Exam> list = examdao.selectByExample(example);
        request.setAttribute("list", list);
        return "home/list";
    }

    /**
     * 获取题目信息
     *
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/getTimu", method = RequestMethod.GET)
    @ResponseBody
    public DataEntity getTimu(Integer id, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        List<Data> list = new ArrayList<Data>();
        Kaoshi kaoshi = kaoshidao.selectByPrimaryKey(id);

        Example example1 = new Example(Test.class);
        List<Test> testlist = testdao.selectByExample(example1);
        // 从单选题题库中随机获取N条数据
        List<Test> list1 = this.suiji(testlist, kaoshi.getNum1());
        for (Test test : list1) {
            Data data1 = new Data();
            data1.setType(1);
            data1.setData(test);
            list.add(data1);
        }

        Example example2 = new Example(Test2.class);
        List<Test2> test2list = test2dao.selectByExample(example2);
        // 从判断题题库中随机获取N条数据
        List<Test2> list2 = this.suiji2(test2list, kaoshi.getNum2());
        for (Test2 test2 : list2) {
            Data data2 = new Data();
            data2.setType(2);
            data2.setData(test2);
            list.add(data2);
        }

        Example example3 = new Example(Test3.class);
        List<Test3> test3list = test3dao.selectByExample(example3);
        // 从填空题题库中随机获取N条数据
        List<Test3> list3 = this.suiji3(test3list, kaoshi.getNum3());
        for (Test3 test3 : list3) {
            Data data3 = new Data();
            data3.setType(3);
            data3.setData(test3);
            list.add(data3);
        }

        Example example4 = new Example(Test4.class);
        List<Test4> test4list = test4dao.selectByExample(example4);
        // 从简答题题库中随机获取N条数据
        List<Test4> list4 = this.suiji4(test4list, kaoshi.getNum4());
        for (Test4 test : list4) {
            Data data = new Data();
            data.setType(4);
            data.setData(test);
            list.add(data);
        }
        return new DataEntity("200", "返回结果", list);
    }

    /**
     * 校验考试信息
     *
     * @param id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/checkExam", method = RequestMethod.GET)
    @ResponseBody
    public DataEntity checkExam(Integer id, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        User user = (User) request.getSession().getAttribute("admin");
        Example example = new Example(Exam.class);
        example.createCriteria().andEqualTo("kid", id).andEqualTo("uid", user.getId());
        List<Exam> list = examdao.selectByExample(example);
        if (list.size() > 0) {
            return new DataEntity("200", "返回结果", list.get(0));
        } else {
            Kaoshi kaoshi = kaoshidao.selectByPrimaryKey(id);
            Exam exam = new Exam();
            exam.setUid(user.getId());
            exam.setUname(user.getName());
            exam.setFen(0);
            exam.setState(0);
            exam.setKid(id);
            exam.setKname(kaoshi.getName());
            exam.setStarttime(MathUtils.currentDateStr());
            examdao.insert(exam);
            list = examdao.selectByExample(example);
            return new DataEntity("200", "返回结果", list.get(0));
        }
    }

    /**
     * 添加考试信息到用户当前考试列表
     *
     * @param idx
     * @param kid
     * @param tid
     * @param daan
     * @param xuan
     * @param isright
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/addExamTimu", method = RequestMethod.POST)
    @ResponseBody
    public DataEntity addExamTimu(Integer idx, Integer kid, Integer tid, String daan,
								  String xuan, Integer isright, String score, String topicType,
								  HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        User user = (User) request.getSession().getAttribute("admin");
        Example example = new Example(Examtime.class);
        example.createCriteria().andEqualTo("kid", kid).andEqualTo("idx", idx).andEqualTo("uid", user.getId());
        List<Examtime> list = examtimedao.selectByExample(example);
		// 考试-用户部分信息赋值
        Examtime examtime = new Examtime();
        if (list.size() > 0) {
            examtime = list.get(0);
        }
		examtime.setIdx(idx);
		examtime.setUid(user.getId());
		examtime.setUname(user.getName());
		// 考试-课程部分信息赋值
		Kaoshi kaoshi = kaoshidao.selectByPrimaryKey(kid);
		examtime.setKid(kaoshi.getId());
		examtime.setKname(kaoshi.getName());
		// 考试-试题部分信息赋值
		examtime.setDaan(daan);
		examtime.setXuan(xuan);
		examtime.setIsright(isright);
		examtime.setCreatedate(MathUtils.currentDateStr());
		switch (topicType) {
			// 选择题部分
			case "1":
				Test test = testdao.selectByPrimaryKey(tid);
				examtime.setTid(test.getId());
				examtime.setTname(test.getName());
				examtime.setScore(test.getScore());
				break;
			// 判断题部分
			case "2":
				Test2 test2 = test2dao.selectByPrimaryKey(tid);
				examtime.setTid(test2.getId());
				examtime.setTname(test2.getName());
				examtime.setScore(test2.getScore());
				break;
			// 填空题部分
			case "3":
				Test3 test3 = test3dao.selectByPrimaryKey(tid);
				examtime.setTid(test3.getId());
				examtime.setTname(test3.getName());
				examtime.setScore(test3.getScore());
				break;
			// 简单题部分
			case "4":
				Test4 test4 = test4dao.selectByPrimaryKey(tid);
				examtime.setTid(test4.getId());
				examtime.setTname(test4.getName());
				// 简单题部分具体获得分值信息从前端传递
				if (isNumeric(score)) {
					examtime.setScore((int)Math.ceil(Double.valueOf(score)));
				}
				break;
			default:
				// 未定义无效题型
				break;
		}
        if (list.size() > 0) {
            examtimedao.updateByPrimaryKey(examtime);
        } else {
            examtimedao.insert(examtime);
        }
        return new DataEntity("200", "返回结果", null);
    }

    /**
     * 交卷评分处理
     *
     * @param kid
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/jiaojuan", method = RequestMethod.POST)
    @ResponseBody
    public DataEntity jiaojuan(Integer kid, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        User user = (User) request.getSession().getAttribute("admin");
        Example example = new Example(Exam.class);
        example.createCriteria().andEqualTo("kid", kid).andEqualTo("uid", user.getId());
        List<Exam> elist = examdao.selectByExample(example);
        if (elist.size() == 0) {
            return new DataEntity("500", "返回结果", "系统错误，请联系管理处理。");
        }
        Exam exam = elist.get(0);
        Example etexample = new Example(Examtime.class);
        etexample.createCriteria().andEqualTo("kid", kid).andEqualTo("uid", user.getId());
        List<Examtime> list = examtimedao.selectByExample(etexample);
        int fen = 0;
        for (Examtime examtime : list) {
            System.out.println(examtime);
            if (examtime.getIsright() == 1) {
                // 计算考试得分
                fen = fen + examtime.getScore();
            }
        }
        exam.setFen(fen);
        exam.setEndtime(MathUtils.currentDateStr());
        exam.setState(1);
        // 修改考试状态等信息
        examdao.updateByPrimaryKey(exam);
        return new DataEntity("200", "返回结果", fen);
    }

    public List<Test> suiji(List<Test> testlist, Integer num) {
        List<Test> list = new ArrayList<Test>();
        for (int i = 1; i <= num; i++) {
            Test test = this.panduan(list, testlist);
            list.add(test);
        }
        return list;
    }

    public List<Test2> suiji2(List<Test2> testlist, Integer num) {
        List<Test2> list = new ArrayList<Test2>();
        for (int i = 1; i <= num; i++) {
            Test2 test = this.panduan2(list, testlist);
            list.add(test);
        }
        return list;
    }

    public List<Test3> suiji3(List<Test3> testlist, Integer num) {
        List<Test3> list = new ArrayList<Test3>();
        for (int i = 1; i <= num; i++) {
            Test3 test = this.panduan3(list, testlist);
            list.add(test);
        }
        return list;
    }

    public List<Test4> suiji4(List<Test4> testlist, Integer num) {
        List<Test4> list = new ArrayList<>();
        for (int i = 1; i <= num; i++) {
            Test4 test = this.panduan4(list, testlist);
            list.add(test);
        }
        return list;
    }

    public Test panduan(List<Test> list, List<Test> testlist) {
        boolean bool = true;
        Test test = testlist.get((int) (Math.random() * (testlist.size())));
        for (Test t : list) {
            if (t.getId() == test.getId()) {
                bool = false;
            }
        }
        if (bool) {
            return test;
        } else {
            return panduan(list, testlist);
        }
    }

    public Test2 panduan2(List<Test2> list, List<Test2> testlist) {
        boolean bool = true;
        Test2 test = testlist.get((int) (Math.random() * (testlist.size())));
        for (Test2 t : list) {
            if (t.getId() == test.getId()) {
                bool = false;
            }
        }
        if (bool) {
            return test;
        } else {
            return panduan2(list, testlist);
        }
    }

    public Test3 panduan3(List<Test3> list, List<Test3> testlist) {
        boolean bool = true;
        Test3 test = testlist.get((int) (Math.random() * (testlist.size())));
        for (Test3 t : list) {
            if (t.getId() == test.getId()) {
                bool = false;
            }
        }
        if (bool) {
            return test;
        } else {
            return panduan3(list, testlist);
        }
    }

    public Test4 panduan4(List<Test4> list, List<Test4> testlist) {
        boolean bool = true;
        Test4 test = testlist.get((int) (Math.random() * (testlist.size())));
        for (Test4 t : list) {
            if (t.getId().equals(test.getId())) {
                bool = false;
            }
        }
        if (bool) {
            return test;
        } else {
            return panduan4(list, testlist);
        }
    }

	/**
	 * 判断字符串是不是double型
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str){
		Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
		Matcher isNum = pattern.matcher(str);
		if(!isNum.matches()){
			return false;
		}
		return true;
	}
}